package com.dengyuanke.upms.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dengyuanke.upms.dto.UserInfo;
import com.dengyuanke.upms.entity.Menu;
import com.dengyuanke.upms.entity.Role;
import com.dengyuanke.upms.entity.User;
import com.dengyuanke.upms.entity.UserRole;
import com.dengyuanke.upms.mapper.UserMapper;
import com.dengyuanke.upms.service.IMenuService;
import com.dengyuanke.upms.service.IUserRoleService;
import com.dengyuanke.upms.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PatchMapping;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author dengyuanke
 * @since 2019-06-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IMenuService menuService;

    /**
     * 通过查用户的全部信息
     *
     * @param user 用户
     * @return
     */
    @Override
    public UserInfo findUserInfo(User user) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUser(user);
        //设置角色列表  （ID）
        List<Long> roleIds = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()))
                .stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        userInfo.setRoles(ArrayUtil.toArray(roleIds, Long.class));

        //设置权限列表（menu.permission）
        Set<String> permissions = new HashSet<>();
        roleIds.forEach(roleId -> {
            List<String> permissionList = menuService.findMenuByRoleId(roleId)
                    .stream()
                    .filter(menu -> StrUtil.isNotBlank(menu.getPermission()))
                    .map(Menu::getPermission)
                    .collect(Collectors.toList());
            permissions.addAll(permissionList);
        });
        userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));
        return userInfo;
    }
}
